package org.cupk2.service.controller;

import com.cupk2.llm.client.handle.impl.SseEmitterHandle;
import com.cupk2.llm.client.inter.Cupk2EmbedClientInter;
import com.cupk2.llm.client.inter.Cupk2LlmClientInter;
import com.cupk2.llm.client.msg.ChatMsg;
import lombok.extern.slf4j.Slf4j;
import org.cupk2.files.service.ResourceFileServiceInter;
import org.cupk2.llm.service.LlmClientServiceInter;
import org.cupk2.tools.web.dto.SendMsgDto;
import org.cupk2.service.utils.CupkAIMsgCacheUtils;
import org.cupk2.zhzm.service.ZhzmKnowServiceInter;
import org.cupk2.tools.db.commons.CupkUUID;
import org.cupk2.tools.web.CupkResponseCode;
import org.cupk2.tools.web.CupkResponseResult;
import org.cupk2.wdap.service.WdapExtendFileServiceInter;
import org.cupk2.wdap.service.WdapTaskServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 知识
 *
 */
@RestController
@RequestMapping("/api/wchat")
@Slf4j
public class WebChatController {
    @Autowired
    private ZhzmKnowServiceInter zhzmKnowServiceImpl;
    @Autowired
    private WdapExtendFileServiceInter wdapExtendFileServiceImpl;
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private WdapTaskServiceInter wdapTaskServiceImpl;
    @Autowired
    private LlmClientServiceInter llmClientServiceImpl;
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    /**
     * 加载知识内容(用于编辑知识)
     *
     * @param msg 对话消息
     * @return
     */
    @PreAuthorize("@cupkAction.has('wchat.creatTalk')")
    @PostMapping("/creattalk")
    public CupkResponseResult creattalk(@RequestBody SendMsgDto msg) {
        Map<String, String> key = new HashMap<>();
        String talkKey = CupkAIMsgCacheUtils.cacheMsg(msg);
        key.put("key", talkKey);
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, key);
    }

    @GetMapping("/stream")
    public SseEmitter stream(@RequestParam String key) {
        SseEmitter emitter = new SseEmitter();
        String uuid = CupkUUID.getUUID32();
        Cupk2LlmClientInter talkClient = llmClientServiceImpl.getTalkClient();
        Cupk2EmbedClientInter embedClient = llmClientServiceImpl.getEmbeddingClient();

        SendMsgDto msg = CupkAIMsgCacheUtils.getMsg(key, talkClient, embedClient);

        executorService.submit(() -> {
            talkClient.sendMsg(new ChatMsg(msg.getFormatMsg(talkClient.getTokenSize()), msg.getHisTalks()), new SseEmitterHandle(emitter, msg));
        });
        return emitter;
    }

}
